//
//  StoresListViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/3/5.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "StoresListViewController.h"
#import "SingleChoseMenu.h"
#import "SearchStoreTableViewCell.h"
#import "CommitStarsView.h"  
#import "ShopViewController.h"
static NSString * cellIndentfier = @"SearchStoreTableViewCell";
@interface StoresListViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UIView *tapyView;
@property (strong, nonatomic) IBOutlet UITableView *tableVIew;
@property (strong, nonatomic) IBOutlet UIView *navSearchView;
@property (strong, nonatomic) IBOutlet UITextField *searchField;
@property (strong, nonatomic) IBOutlet UITableView *tapysTableView;
@property (strong, nonatomic) IBOutlet UILabel *shopBagNumber;
@property(nonatomic,strong)NSMutableArray * storeArray;
@property(nonatomic,strong)NSMutableArray * typesArray;
@property (strong, nonatomic) NSMutableArray *storeClassifyArrary;
@property (strong, nonatomic) NSString *classifyType;//分类类型 1分类 2其他
@property(nonatomic,strong)NSDictionary * choseTypeDic;
@property(nonatomic,strong)NSString * floorStr;
@property(nonatomic,strong)NSString * typeStr;
@property(nonatomic,strong)NSString * pickStr;
@property (strong, nonatomic) IBOutlet UIButton *floorButton;
@property (strong, nonatomic) IBOutlet UIButton *typeButton;
@property (strong, nonatomic) IBOutlet UIButton *choseButton;
@property (strong, nonatomic) IBOutlet UIButton *maskButton;
@property (strong, nonatomic) IBOutlet UIButton *floorSmallButton;
@property (strong, nonatomic) IBOutlet UIButton *typeSmallButton;
@property (strong, nonatomic) IBOutlet UIButton *choseSmallButton;
@property(nonatomic,strong)UIButton * currentButton;
@end



@implementation StoresListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if (self.searchStr) {
        _searchField.text = self.searchStr;
    }
    _pageNO =  1;
    self.classifyType = @"2";
    self.typesArray = [NSMutableArray array];
    _storeArray = [NSMutableArray array];
    self.storeClassifyArrary = [NSMutableArray array];
    _choseTypeDic = [@{@"floor":@"",@"type":@"",@"pick":@""}mutableCopy];
    _floorStr = @"";
    _typeStr = @"";
    _pickStr = @"";
    [self initViewLayout];
    [self getBagNumber];
    [self getTypes];
    [self addRefreshing];
    // Do any additional setup after loading the view.
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.tapyView];
    [self adaptiveViewLayout:self.navSearchView];
    
    
    self.shopBagNumber.layer.masksToBounds = YES;
    self.shopBagNumber.layer.cornerRadius = 6*VerticalRatio();
    self.navSearchView.layer.masksToBounds = YES;
    self.navSearchView.layer.cornerRadius = 17*VerticalRatio();
    self.navSearchView.layer.borderWidth = 1;
    self.navSearchView.layer.borderColor = kGetColor(230, 230, 230).CGColor;
    
    _searchField.delegate = self;
   
    //滚动搜索类型
    ScroTitleView * scroTitle = [[ScroTitleView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 50, 35), NO) Titles:@[@"商品",@"品牌",@"店铺"] complect:^(NSInteger index) {
        
    }];
    [self.navSearchView addSubview:scroTitle];
    
    [self.tableVIew registerNib:[UINib nibWithNibName:cellIndentfier bundle:nil] forCellReuseIdentifier:cellIndentfier];
    _tableVIew.scrollEnabled = YES;
    _tapysTableView.dataSource = self;
    _tapysTableView.delegate = self;
}

- (IBAction)back:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}
- (void)getStoresList{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:_searchField.text forKey:@"search"];
    [dic setObject:_floorStr forKey:@"mstoStair"];
    [dic setObject:_typeStr forKey:@"mstoTypeId"];
    [dic  setObject:[NSNumber numberWithInteger:self.pageNO]     forKey:@"currentPage"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryShopRanking withHttpType:@"POST" withTag:SX_SX_queryShopRanking];
    
}


- (void)getTypes{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryShopTypes withHttpType:@"POST" withTag:SX_SX_queryShopTypes];
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableVIew.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableVIew.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求商家数据
            [self getStoresList];
        });
    }];
    // 马上进入刷新状态
    [self.tableVIew.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.storeArray.count == _totle) {
        [self.tableVIew.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求商家数据
            [self getStoresList];
        });
    }
    
}


#pragma mark  获取购物袋数量--=========================================
-(void)getBagNumber{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"queryCartProductTotalNum" forKey:@"method"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"userId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryCartProductTotalNum withHttpType:@"POST" withTag:SX_QueryCartProductTotalNum];
}

- (IBAction)choseTypeHandel:(UIButton*)sender {
    [_typesArray removeAllObjects];
    
    UIButton * button = [[UIButton alloc]init];
    if (sender == _floorButton) {
        button = _floorSmallButton;
    }else if(sender == _choseButton){
        button = _choseSmallButton;
    }else{
        button = _typeSmallButton;
    }
    
    if (button != _currentButton) {
        [_currentButton.layer addAnimation:[self rotation:0.3 degree:2*M_PI direction:1 repeatCount:0] forKey:nil];
        _currentButton = button;
    }
    if (sender == _floorButton) {
        _floorButton.selected = YES;
        _floorSmallButton.selected = YES;
        _typeButton.selected = NO;
        _typeSmallButton.selected = NO;
        _choseButton.selected = NO;
        _choseSmallButton.selected = NO;
        [_floorSmallButton.layer addAnimation:[self rotation:0.3 degree:M_PI direction:1 repeatCount:0] forKey:nil];
        _typesArray =[@[@"全部",@"B1休闲美食",@"1F时尚服饰",@"2F儿童主题",@"3F名表饰品",@"4F餐饮美食",@"5F休闲娱乐"]mutableCopy];
        //            _tapysTableView.dataSource = self;
        //            _tapysTableView.delegate = self;
        [_tapysTableView reloadData];
    }else if (sender == _typeButton){
        _floorButton.selected = NO;
        _floorSmallButton.selected = NO;
        _typeButton.selected = YES;
        _typeSmallButton.selected = YES;
        _choseButton.selected = NO;
        _choseSmallButton.selected = NO;
        [_typeSmallButton.layer addAnimation:[self rotation:0.3 degree:M_PI direction:1 repeatCount:0] forKey:nil];
        if (self.storeClassifyArrary.count < 1) {
            [self getTypes];
        }else{
            [_tapysTableView reloadData];
        }
        
    }else{
        _floorButton.selected = NO;
        _floorSmallButton.selected = NO;
        _typeButton.selected = NO;
        _typeSmallButton.selected = NO;
        _choseButton.selected = YES;
        _choseSmallButton.selected = YES;
        [_choseSmallButton.layer addAnimation:[self rotation:0.3 degree:M_PI direction:1 repeatCount:0] forKey:nil];
        _typesArray =[@[@"默认",@"销量最高",@"折扣优惠"]mutableCopy];
        //            _tapysTableView.dataSource = self;
        //            _tapysTableView.delegate = self;
        [_tapysTableView reloadData];
    }
    
    [UIView animateWithDuration:0.5 animations:^{
        if(_typeButton.selected){
            _tapysTableView.frame = flexibleFrame(CGRectMake(0, 109, 320, 45*_storeClassifyArrary.count), YES);
        }else{
            _tapysTableView.frame = flexibleFrame(CGRectMake(0, 109, 320, 45*_typesArray.count), YES);
        }
        
    }completion:^(BOOL finished) {
        _maskButton.hidden = NO;
    }];

    
   

}
- (IBAction)closeTypes:(UIButton *)sender {
    _maskButton.hidden = YES;
    [UIView animateWithDuration:0.5 animations:^{
        _tapysTableView.frame = flexibleFrame(CGRectMake(0, 109, 320, 0), YES);
    }];
    [_currentButton.layer addAnimation:[self rotation:0.3 degree:2*M_PI direction:1 repeatCount:0] forKey:nil];
  }
#pragma mark ====旋转动画======
-(CABasicAnimation *)rotation:(float)dur degree:(float)degree direction:(int)direction repeatCount:(int)repeatCount
{
    CATransform3D rotationTransform = CATransform3DMakeRotation(degree, 0, 0, direction);
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
    animation.toValue = [NSValue valueWithCATransform3D:rotationTransform];
    animation.duration  =  dur;
    animation.autoreverses = NO;
    animation.cumulative = NO;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.repeatCount = repeatCount;
    animation.delegate = self;
    
    return animation;
    
}
#pragma mark === 前往购物车
- (IBAction)goToShopBag:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    UIViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"ShoppingBag"];
    [self.navigationController   pushViewController:page animated:YES];
}


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    if ([string isEqualToString:@"\n"]) {
        [self addRefreshing];
        [[[UIApplication sharedApplication]keyWindow]endEditing:YES];
        return NO;
    }
    return YES;
}


#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _tableVIew) {
        return 95*VerticalRatio();

    }else{
        return 45*VerticalRatio();
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _tapysTableView) {
        if (_typeButton.selected) {
            return _storeClassifyArrary.count;
        }
        return _typesArray.count;
    }else{
    return _storeArray.count;
    }
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView != _tableVIew) {
        static NSString * cellIdentifier = @"CELL";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell==nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        
        for (UIView *view in cell.subviews) {
            if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
                [view removeFromSuperview];
            }
        }
            UIImageView  * imageView = [[UIImageView alloc]initWithFrame:flexibleFrame(CGRectMake(300, 16, 8, 13), YES)];
            imageView.image = [UIImage imageNamed:@"jiantou"];
        
            
            UILabel * label = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(15, 0, 280, 45), YES)];
        
            label.textColor = [UIColor colorWithWhite:0.094 alpha:1.000];
            label.textAlignment = NSTextAlignmentLeft;
            label.font = [UIFont systemFontOfSize:15*VerticalTexeRatio()];
            if (_typeButton.selected) {
                label.text = [NSString stringWithFormat:@"%@",_storeClassifyArrary[indexPath.row][@"mstyName"]];
                if (indexPath == _choseTypeDic[@"type"]) {
                    label.textColor = [UIColor colorWithRed:1.000 green:0.647 blue:0.035 alpha:1.000];
                }
            }else{
                label.text = _typesArray[indexPath.row];
                if (_floorButton.selected) {
                    if (indexPath == _choseTypeDic[@"floor"]) {
                        label.textColor = [UIColor colorWithRed:1.000 green:0.647 blue:0.035 alpha:1.000];
                    }
                }else{
                    if (indexPath == _choseTypeDic[@"pick"]) {
                        label.textColor = [UIColor colorWithRed:1.000 green:0.647 blue:0.035 alpha:1.000];
                    }
                }
            }
            [cell addSubview:imageView];
            [cell addSubview:label];
            
            UIView * line = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 44, 320, 1), YES)];
            line.backgroundColor = [UIColor colorWithWhite:0.949 alpha:1.000];
            [cell addSubview:line];
        return cell;
    }else{
    SearchStoreTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentfier];
    if (cell == nil) {
        cell= [[SearchStoreTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentfier];
        
    }
    
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    
    
    
    
    NSString * image = _storeArray[indexPath.row][@"mstoImag"];
    if (image.length>0) {
        [cell.storeImage sd_setImageWithURL:[NSURL URLWithString:image]];
    }else{
    cell.storeImage.image = [UIImage imageNamed:@"collection5"];
    }
    cell.storeName.text = _storeArray[indexPath.row][@"mstoName"];
    cell.storeAddress.text = _storeArray[indexPath.row][@"mstoAddress"];
    CGFloat score;
    if([_storeArray[indexPath.row][@"storeScore"] isEqual:[NSNull null]]){
        score = 5;
    }else{
        score = [[NSString stringWithFormat:@"%.1f",[_storeArray[indexPath.row][@"storeScore"]floatValue]] floatValue]/2;
    }
    CommitStarsView * starts = [[CommitStarsView alloc]initWithFrame:flexibleFrame(CGRectMake(118, 37, 75, 15), YES) Stars:score];
    [cell addSubview:starts];
        
    cell.scoreLabel.text = [NSString stringWithFormat:@"%.1f分",score];
    cell.storeTypeLabel.text = [NSString stringWithFormat:@"%@",_storeArray[indexPath.row][@"mstyName"]];
    return cell;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView != _tableVIew) {
        if (_floorButton.selected) {
            [_choseTypeDic setValue:indexPath forKey:@"floor"];
            if(indexPath.row == 0){
                _floorStr = @"";
            }else{
              _floorStr = [NSString stringWithFormat:@"%ld",indexPath.row-1];
            }
            [_floorButton setTitle:_typesArray[indexPath.row] forState:UIControlStateNormal];
            
            CGSize size = [_floorButton.titleLabel.text sizeWithFont:_floorButton.titleLabel.font];
            if (size.width>_floorButton.frame.size.width) {
                size.width = _floorButton.frame.size.width-_floorSmallButton.frame.size.width;
            }
            _floorSmallButton.frame =CGRectMake(CGRectGetMinX(_floorButton.frame)+(_floorButton.frame.size.width-size.width)/2+size.width+1, _floorSmallButton.frame.origin.y, _floorSmallButton.frame.size.width, _floorSmallButton.frame.size.height);
        }else if(_typeButton.selected){
            [_choseTypeDic setValue:indexPath forKey:@"type"];
            _typeStr = [NSString stringWithFormat:@"%@",_storeClassifyArrary[indexPath.row][@"mstyId"]];
            [_typeButton setTitle:_storeClassifyArrary[indexPath.row][@"mstyName"] forState:UIControlStateNormal];
            
            CGSize size = [_typeButton.titleLabel.text sizeWithFont:_typeButton.titleLabel.font];
            if (size.width>_typeButton.frame.size.width) {
                size.width = _typeButton.frame.size.width-_typeSmallButton.frame.size.width;
            }
            _typeSmallButton.frame =CGRectMake(CGRectGetMinX(_typeButton.frame)+(_typeButton.frame.size.width-size.width)/2+size.width+1, _typeSmallButton.frame.origin.y, _typeSmallButton.frame.size.width, _typeSmallButton.frame.size.height);
        }else{
            [_choseTypeDic setValue:indexPath forKey:@"pick"];
            _pickStr = [NSString stringWithFormat:@"%@",_typesArray[indexPath.row]];
            [_choseButton setTitle:_typesArray[indexPath.row] forState:UIControlStateNormal];
            
            CGSize size = [_choseButton.titleLabel.text sizeWithFont:_choseButton.titleLabel.font];
            if (size.width>_choseButton.frame.size.width) {
                size.width = _choseButton.frame.size.width-_choseSmallButton.frame.size.width;
            }
            _choseSmallButton.frame =CGRectMake(CGRectGetMinX(_choseButton.frame)+(_choseButton.frame.size.width-size.width)/2+size.width+1, _choseSmallButton.frame.origin.y, _choseSmallButton.frame.size.width, _choseSmallButton.frame.size.height);
        }
        
        
        [self addRefreshing];
        _maskButton.hidden = YES;
        [UIView animateWithDuration:0.5 animations:^{
            _tapysTableView.frame = flexibleFrame(CGRectMake(0, 109, 320, 0), YES);
        }];
        [_currentButton.layer addAnimation:[self rotation:0.3 degree:2*M_PI direction:1 repeatCount:0] forKey:nil];
        
    }else{
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
        ShopViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"Shop"];
        page.storeId = _storeArray[indexPath.row][@"mstoId"];
        [self.navigationController   pushViewController:page animated:YES];
    }

    
   
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableVIew.header endRefreshing];
    [_tableVIew.footer endRefreshing];
   if (tag == SX_QueryCartProductTotalNum){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            _shopBagNumber.text =[NSString stringWithFormat:@"%@", database[@"result"]];
        }
        
   }else if (tag == SX_SX_queryShopRanking){
       if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
           
           [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
           
       }else  {
           dispatch_async(dispatch_get_main_queue(), ^{
               _totle = [database[@"result"][@"totalResults"] integerValue];
               if (_totle > PageSize) {
                   __weak __typeof(self) weakSelf = self;
                   if (!self.tableVIew.footer) {
                       // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                       self.tableVIew.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                           [weakSelf loadMoreData];
                       }];
                   }
               }
               if (self.pageNO == 1) {
                   [self.storeArray removeAllObjects];
               }
               NSArray *arr = database[@"result"][@"pageRecord"];
               for (id entity in arr) {
                   [self.storeArray addObject:entity];
               }
               _tableVIew.dataSource = self;
               _tableVIew.delegate = self;
               [_tableVIew reloadData];
               
           });
       }
   }else if (tag == SX_SX_queryShopTypes){
       if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
           
           [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
           
       }else  {
           _storeClassifyArrary = database[@"result"];
           _tapysTableView.dataSource = self;
           _tapysTableView.delegate = self;
           [_tapysTableView reloadData];
           
       }
   }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    [self dismissWaitDialog];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
